#ifndef MQTTCLIENT_H
#define MQTTCLIENT_H

#include <QObject>
#include "qmqttclient.h"
#include "qmqtt_global.h"

class MqttClient : public QObject
{
    Q_OBJECT
public:
    explicit MqttClient(QObject *parent = nullptr);

    Q_PROPERTY(QString  deviceId    READ  deviceId  WRITE setDeviceId   NOTIFY deviceIdChanged)

    // 设置MQTT服务器地址，并自动解析为IP
    const QString       host      () { return _host; }
    // 获取设备ID（用作ClientId）
    QString deviceId   () { return _deviceId; }
    void setDeviceId   (const QString deviceId) {
        _deviceId = deviceId;
    };

    Q_PROPERTY(QString subTopic READ subTopic WRITE setSubTopic NOTIFY subTopicChanged)
    Q_PROPERTY(bool connected READ isConnected NOTIFY connectedChanged)
    Q_PROPERTY(QString lastTopic READ lastTopic NOTIFY messageChanged)
    Q_PROPERTY(QString lastMessage READ lastMessage NOTIFY messageChanged)
    Q_PROPERTY(QString message READ message NOTIFY messageChanged)

    Q_INVOKABLE void setHost(const QString &host);
    Q_INVOKABLE void setPort(int port);
    Q_INVOKABLE void connectToHost();
    Q_INVOKABLE void disconnectFromHost();
    // Q_INVOKABLE void connectToHost(const QString &host, int port);
    Q_INVOKABLE void subscribeTopic(const QString &topic);
    Q_INVOKABLE void publishMessage(const QString &msg);
    Q_INVOKABLE void publishMessage(const QString &topic, const QString &msg,
                                    int qos = 0, bool retain = false);
    //READ
    bool isConnected() const { return _mqttClient->isConnectedToHost(); }
    QString lastTopic() const { return _lastTopic; }
    QString lastMessage() const { return _lastMessage; }
    QString message() const { return _message; }
    QString subTopic() const { return _subTopic; }
    void setSubTopic(const QString &topic);

signals:
    void hostChanged();
    void deviceIdChanged();
    void messageChanged();
    void connectedChanged();
    void subTopicChanged();
    void messageReceived(const QString &topic, const QByteArray &msg);   // 新增信号
    void forwardPrepared(const QByteArray &forwardMsg);

public slots:
    // void readBytes(QByteArray msg);
    void readBytes(const QString &topic, const QByteArray &msg);
    void onMessageReceived(QByteArray msg) ;
    void onConnected();
    void onDisconnected();
    void checkConnection();

private:
    QString _host;
    QString _deviceId;
    QMQTTClient*        _mqttClient;
    int                 _port;
    QString _message;
    QString _lastTopic;
    QString _lastMessage;
    QString _subTopic;

    QTimer *reconnectTimer;

};

#endif // MQTTCLIENT_H
